﻿/* 2013/10/22 */
using System;
using System.Runtime.InteropServices;

namespace Cosmos.Windows.Forms
{
    /// <summary>
    /// Provides methods to extend glass frame into form background.
    /// </summary>
    public sealed class NonClientRegionAPI
    {
        [StructLayout(LayoutKind.Sequential)]
        struct MARGINS
        {
            public int Left;
            public int Right;
            public int Top;
            public int Bottom;
        }

        [DllImport("dwmapi.dll", PreserveSig = false)]
        static extern void DwmExtendFrameIntoClientArea(IntPtr hwnd, ref MARGINS margins);

        [DllImport("dwmapi.dll", PreserveSig = false)]
        static extern bool DwmIsCompositionEnabled();

        public static void Load(IntPtr hwnd, int width, int height)
        {
            Load(hwnd, width, height, width, height);
        }

        public static void Load(IntPtr hwnd, int left, int top, int right, int bottom)
        {
            if (DwmIsCompositionEnabled())
            {
                MARGINS margins = new MARGINS();
                margins.Left = left;
                margins.Top = top;
                margins.Right = right;
                margins.Bottom = bottom;
                DwmExtendFrameIntoClientArea(hwnd, ref margins);
            }
        }

        public static void PaintBackground(System.Windows.Forms.PaintEventArgs e)
        {
            PaintBackground(e, System.Drawing.Color.Black);
        }

        public static void PaintBackground(System.Windows.Forms.PaintEventArgs e, System.Drawing.Color color)
        {
            if (DwmIsCompositionEnabled())
            {
                e.Graphics.Clear(color);
            }
        }
    }
}
